﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace CP.DBService
{
    public class EntityAdapter<TEntity>
    {
        private static EntityAdapter<TEntity> adp;

        public static EntityAdapter<TEntity> CreateInstance()
        {
            if (adp == null)
                adp = new EntityAdapter<TEntity>();
            return adp;
        }
        public IList<TEntity> Parse<TSource>(IEnumerable<TSource> SourceModes)
        {
            if (SourceModes == null)
                return null;

            IList<TEntity> entities = new List<TEntity>();
            foreach (var mode in SourceModes)
            {
                TEntity entity = Activator.CreateInstance<TEntity>();
                PropertyInfo[] mps = mode.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                PropertyInfo[] eps = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

                foreach (var mp in mps)
                {
                    var ep = eps.Where(e => e.Name == mp.Name).First();
                    if (ep != null)
                    {
                        ep.SetValue(entity, mp.GetValue(mode, null), null);
                    }
                }
                entities.Add(entity);
            }

            return entities;
        }
    }
}
